<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->

        <el-table-column prop="name" align="center" width="200" label="角色">
          <template v-slot="{ row }">
            <!-- 条件判断 -->
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else> {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click="updateConfirm(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <!-- 非编辑状态 -->
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)" style="margin-right: 15px;">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->

        <el-pagination :page-size="pageParams.pagesize" :current-page="pageParams.page" :total="pageParams.total"
          layout="prev, pager, next" @current-change="changePage" />
      </el-row>
    </div>
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="cancelBtn">
      <!-- 表单内容 -->
      <el-form label-width="120px" ref="roleForm" :model="roleForm" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input style="width:300px" size="mini" v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch size="mini" v-model="roleForm.state" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input type="textarea" v-model="roleForm.description" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="confirmBtn">确定</el-button>
              <el-button size="mini" @click="cancelBtn">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 放置权限弹层 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <!-- 放置权限数据 -->
      <el-tree node-key="id" :data="permissionData" :props="{ label: 'name' }" show-checkbox default-expand-all
        :default-checked-keys="permIds" ref="permTree" />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>

  </div>
</template>
<script>
import { getrolesListApi, addRoleApi, updateRole, delRoleApi, getRoleDetail, assignPerm } from '@/api/role'
import { getPermissionListApi } from '@/api/permission'
import { transListToTreeData } from '@/utils/index'
export default {
  name: 'Role',
  data() {
    return {
      showDialog: false,
      list: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      roleForm: {
        "name": "",
        "description": "",
        "state": 0 //1表示启用0未启用
      },
      rules: {
        "name": [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        "description": [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null,
      permIds: []
    }
  },
  methods: {
    async getrolesList() {
      const { total, rows } = await getrolesListApi(this.pageParams)
      this.list = rows
      this.list.forEach(item => {
        // item.isEdit = false // 添加一个属性 初始值为false
        // 数据响应式的问题  数据变化 视图更新
        // 添加的动态属性 不具备响应式特点
        // this.$set(目标对象, 属性名称, 初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(item, "isEdit", false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.pageParams.total = total
    },
    async addRole() {
      console.log(this.roleForm)
      await addRoleApi(this.roleForm)
      this.$message.success('添加角色成功！')
    },
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getrolesList()

    },
    cancelBtn() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
    },
    confirmBtn() {
      this.$refs.roleForm.validate(async isOk => {
        if (isOk) {
          await this.addRole()
          this.cancelBtn()
          await this.getrolesList()
        }
      })
    },
    btnEditRow(row) {
      row.isEdit = true // 改变行的编辑状态
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async updateConfirm(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ ...row.editRow, id: row.id })
        this.$message.success("更新角色信息成功！")
        Object.assign(row, { ...row.editRow, isEdit: false })
      } else {
        this.$message.error("角色名称和描述都不能为空！")
      }
    },
    async confirmDel(id) {
      await delRoleApi(id)
      this.$message.success('删除角色成功')
      if (this.list.length === 1 && this.pageParams.page > 1) this.pageParams.page--
      this.getrolesList()
    },
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.permissionData = transListToTreeData(await getPermissionListApi(), 0)
      this.showPermissionDialog = true
    },
    async btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    }
  },
  created() {
    this.getrolesList()
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
